const handleUserRoute = require('./src/routes/user')
const handleHomeRoute = require('./src/routes/home')
const handleGoodRoute = require('./src/routes/good')
const handleCategoryRoute = require('./src/routes/category')
const handleRecommendRoute = require('./src/routes/recommend')
const handleGoodDetailRoute = require('./src/routes/detail')
const handleLoginRoute = require('./src/routes/login')
const handleRegisterRoute = require('./src/routes/register')
const handleOrderRoute = require('./src/routes/order')

const {
    URLSearchParams
} = require('url');


const {
    verifyToken,
    getUserId,
    formate
} = require('./src/utils')

//处理Post数据
const getPostData = (req) => {
    const promise = new Promise((resolve, reject) => {
        if (req.method !== 'POST' || req.headers['content-type'] !== 'application/json') {
            resolve({});
            return;
        }

        let postData = '';

        req.on('data', (chunk) => {
            postData += chunk;
        })

        req.on('end', () => {
            if (!postData) {
                resolve({});
                return;
            }
            resolve(
                JSON.parse(postData)
            )
        })
    })

    return promise;
}

const serverHandler = (req, res) => {
 res.setHeader('Content-Type', 'application/json;charset=utf-8');
    // res.setHeader('Content-Type', 'application/json');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader("Access-Control-Allow-Headers","X-Requested-With, accept, origin, content-type,Authorization");
    res.setHeader('Access-Control-Allow-Methods', 'POST','OPTIONS','GET');
    res.setHeader('Access-Control-Allow-Age',3600);

    if(req.method == 'OPTIONS'){
        res.end(JSON.stringify({statusCode:200})) 
        return;
    }
    req.path = req.url.split('?')[0];
    req.query = formate(new URLSearchParams(req.url.split('?')[1]));
    
    let token = req.headers.authorization || req.headers.Authorization;
    

    let path = req.path.split('/')[1];
    let handlerRoute;
   
    let tag =  verifyToken(token).tag;
    let resolveRouteError = (tag)=>{
        console.log('tokenTAG',tag);
        if(tag === 2 ){
         res.writeHead(244, {
                'Content-Type': "text/plain"
            });
           res.write('Expired Authorization');
           res.end()
        }else{
            res.writeHead(245, {
                'Content-Type': "text/plain"
            });
          res.write('Invalid Authorization');
           res.end()
        }
        
        
    }
    
    console.log('query',req.query,'body',req.body,'path',path,'method',req.method,'tag',tag);

    //异步处理post请求
    getPostData(req).then((posData) => {
        req.body = posData
        
        switch (path) {
        case 'category':
            handlerRoute = handleCategoryRoute;
            break;
        case 'good':
            handlerRoute = handleGoodRoute;
            break;
        case 'home':
            handlerRoute = handleHomeRoute;
            break;
        case 'recommend':
            handlerRoute = handleRecommendRoute;
            break;
        case 'detail':
            handlerRoute = handleGoodDetailRoute;
            break;
        case 'login':
            handlerRoute = handleLoginRoute;
            break;
        case 'register':
            handlerRoute = handleRegisterRoute;
            break;
        case 'order':
            if(tag == 1){
              req.body.uid = getUserId(token);
              req.query.uid = req.body.uid;
            handlerRoute = handleOrderRoute;
            }
            else{
                resolveRouteError(tag)
                return;
            }
            break;
        case 'user':
            if(tag == 1){
              req.body.uid = getUserId(token);
              req.query.uid = req.body.uid;
              handlerRoute = handleUserRoute;
            }
            else{
                resolveRouteError(tag)
                return;
            }
            break;
        default: {
            //路由请求错误修改请求头并提示404
            resolveRouteError(tag)
            return;
        };
    }
        
        
        const userDataPromise = handlerRoute(req, res);

        if (userDataPromise) {
            userDataPromise.then((userData) => {
                res.end(JSON.stringify(userData))
            })
            return;
        }
    })
}

module.exports = serverHandler;